local M = {}

local json = require("json")

-- 带有属性功能的表
local function newproperties()
	local t = {}

	local getters =  {}
	local setters = {}

	t.getters = getters

	-- TODO 暂时没有考虑self的问题
	t.__index = function(self, key)
		local getter = getters[key]

		if getter then
			if type(getter) == "table" then
				return getter
			elseif type(getter) == "function" then
				return getter(self, key)
			end
		end
	end

	-- TODO 暂时没有考虑self的问题
	t.__newindex = function(self, key, value)
		local settter = setters[key]
		if settter then
			if type(setter) == "table" then
				return setter
			else
				return setters[key](self, key, value)
			end
		end
	end

	-- 设置对应属性
	function t:setProperty(key, getter, setter)
		getters[key] = getter
		setters[key] = setter
	end

	function t:setTableProperty(key, t1)
		getters[key] = t1
		setters[key] = t1
	end

	local function copyProps(tOri, tDest)
		for k, v in pairs(tOri.getters) do
			local value = tOri[k]
			if type(value) == "table" and value.getters then
				print(value)
				tDest[k] = {}
				copyProps(value, tDest[k])
			else
				print(k, value)
				tDest[k] = value
			end
		end
	end

	-- 此方法主要是给编辑器用的
	function t:properties2json()
		local t1 = {}
		copyProps(self, t1)
		return json.encode(t1)
	end

	setmetatable(t, t)

	return t
end


function M.testParent()
	local rect = display.newRect(200, 200, 100, 100)

	local meta = getmetatable((rect))

	local oldIndex = meta.__index
	local oldNewIndex = meta.__newindex

	rect.__index = function(t, key)
		print("index ", key)
		return oldIndex(t, key)
	end

	rect.__newindex = function(t, key, value)
		print("newIndex", key, value)
	end

	setmetatable(rect, rect)

	local g = display.newGroup()

	g:insert(rect)
	print(rect.parent)
end

function M.testUserData()
	local rect = display.newRect(200, 200, 100, 100)

	local path = rect.path

	local meta = getmetatable((path))

	local oldIndex = meta.__index
	local oldNewIndex = meta.__newindex

	meta.__index = function(t, key)
		print("index ", key)
		return oldIndex(t, key)
	end

	meta.__newindex = function(t, key, value)
		print("newIndex", key, value)
		return oldNewIndex(t, key, value)
	end
end

function M.test()
	M.testUserData()
end


return M